<template>
  <div style="margin-left: -20px;margin-top: -60px;margin-bottom: -10px;">
    <body>
      <div class="container right-panel-active">
        <!-- 登录 -->
        <div class="container__form container--signup">
          <el-form
            :model="loginForm"
            ref="loginForm"
            :rules="rules"
            action="#"
            class="form"
            id="form2"
          >
            <h1 style="font-weight: bold;" class="form__title">登 录</h1>
            <el-form-item v-if="show" prop="account">
              <el-input
                type="text"
                maxlength="11"
                placeholder="手机号/用户名"
                v-model="loginForm.account"
                style="width: 300px;"
              />
            </el-form-item>
            <el-form-item v-if="show" prop="userPass">
              <el-input
                placeholder="密码"
                type="text"
                v-model="loginForm.userPass"
                autocomplete="off"
                style="width: 300px;"
              >
              </el-input>
            </el-form-item>
            <el-form-item v-if="showCode" prop="userPhone">
              <el-input
                type="text"
                maxlength="11"
                placeholder="手机号"
                v-model="loginForm.userPhone"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item v-if="showCode" prop="code">
              <el-input
                type="text"
                maxlength="6"
                placeholder="验证码"
                v-model="loginForm.code"
                style="width: 166px"
              />
              <el-button :disabled="loginDisabled" @click="getLoginCode">{{
                loginValiBtn
              }}</el-button>
            </el-form-item>
            <el-form-item>
              <el-button class="btn" type="primary" @click="login('loginForm')"
                >登 录</el-button
              >
            </el-form-item>
            <div v-if="show" class="login-transfer">或使用<button @click="loginByPhone('loginForm')" class="login-btn-text">短信验证码</button>登录</div>
            <div v-if="showCode" class="login-transfer">或使用<button @click="loginByaccount('loginForm')" class="login-btn-text">账号密码</button>登录</div>
            <a style="margin-top: 20px; margin-left: 200px;" href="#/backLogin"
              >管理员登录</a
            >
          </el-form>
        </div>

        <!-- 注册 -->
        <div class="container__form container--signin">
          <h1>注 册</h1>
          <div style="width: 300px;margin-left: 40px;">
            <el-form
              :model="ruleForm"
              status-icon
              :rules="rules"
              ref="ruleForm"
              class="demo-ruleForm"
              id="form1"
            >
              <el-form-item prop="userName">
                <el-input
                  type="text"
                  placeholder="用户名"
                  v-model="ruleForm.userName"
                  style="width: 300px;"
                />
              </el-form-item>
              <el-form-item prop="userPass">
                <el-input
                  placeholder="密码"
                  type="text"
                  v-model="ruleForm.userPass"
                  autocomplete="off"
                >
                </el-input>
              </el-form-item>
              <el-form-item prop="userPhone">
                <el-input
                  type="text"
                  maxlength="11"
                  placeholder="手机号"
                  v-model="ruleForm.userPhone"
                />
              </el-form-item>
              <el-form-item prop="code">
                <el-input
                  type="text"
                  maxlength="6"
                  placeholder="验证码"
                  v-model="ruleForm.code"
                  style="width: 183px"
                />
                <el-button :disabled="disabled" @click="getCode">{{
                  valiBtn
                }}</el-button>
              </el-form-item>
              <el-form-item>
                <el-button
                  class="btn"
                  type="primary"
                  @click="submitForm('ruleForm')"
                  >注 册</el-button
                >
                <el-button @click="resetForm('ruleForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- Overlay -->
        <div class="container__overlay">
          <div class="overlay">
            <div class="overlay__panel overlay--left">
              <button
                class="btn"
                @click="resetLoginForm('loginForm')"
                id="signIn"
              >
                注 册
              </button>
            </div>
            <div class="overlay__panel overlay--right">
              <button class="btn" @click="resetForm('ruleForm')" id="signUp">
                登 录
              </button>
            </div>
          </div>
        </div>
      </div>
    </body>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    var checkPhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入绑定的手机号码"));
      } else if (
        !/^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/.test(
          value
        )
      ) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    var checkCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else if (!/^[0-9]+$/.test(value) || !/^\d{6}$/.test(value)) {
        callback(new Error("请输入6位数字的验证码"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      }
      //它的意思是 当符合要求的条件的时候，就触发回调函数。这个回调的函数是显示成功的标识
      setTimeout(() => {
        if (!/^[0-9A-Za-z]{6}$/.test(value)) {
          return callback(new Error("密码必须为6位的数字或字母"));
        } else {
          if (this.ruleForm.checkPass !== "") {
            this.$refs.ruleForm.validateField("checkPass");
          }
          callback();
        }
      }, 500);
    };
    var validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.userPass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      repeatPwd: "",
      ruleForm: {
        userPass: "",
        userName: "",
        userPhone: "",
        code: ""
      },
      loginForm: {
        account: "",
        userPass: "",
        userPhone:'',
        code:''
      },
      show: false,
      showCode:true,
      rules: {
        userPass: [
          {
            validator: validatePass,
            trigger: "blur"
          }
        ],
        userPhone: [
          {
            validator: checkPhone,
            required: true,
            trigger: "blur"
          }
        ],
        code: [
          {
            validator: checkCode,
            required: true,
            trigger: "blur"
          }
        ],
        userName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          }
        ],
        account: [
          {
            required: true,
            message: "请输入电话或用户名",
            trigger: "blur"
          }
        ]
      },
      valiBtn: "获取验证码",
      disabled: false,
      loginValiBtn:"获取验证码",
      loginDisabled:false
    };
  },
  methods: {
    login(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          //登录操作
          this.$http.post("/userInfo/login", this.loginForm).then(resp => {
            if (resp.data.code == 200) {
              sessionStorage.setItem("userId", resp.data.data.userId);
              sessionStorage.setItem(
                "loginUser",
                JSON.stringify(resp.data.data)
              );
              alert(resp.data.message);
              this.$router.push("/showUbookInfo");
            } else {
              //登录失败
              alert(resp.data.message);
              this.loginForm.account = "";
              this.loginForm.userPass = "";
              this.loginForm.code = "";
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          //注册操作
          this.$http.post("/userInfo/register", this.ruleForm).then(resp => {
            if (resp.data.code == 200) {
              this.resetForm(formName);
              alert(resp.data.message);
            } else {
              alert(resp.data.message);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    resetLoginForm(formName) {
      this.$refs[formName].resetFields();
    },
    //获取验证码 并只验证手机号 是否正确
    getCode() {
      this.$refs["ruleForm"].validateField("userPhone", err => {
        if (err) {
          console.log("未通过");
          return;
        } else {
          console.log("已通过");
          this.$http
            .get(
              "/userInfo/sendRegisterCode?userPhone=" + this.ruleForm.userPhone
            )
            .then(resp => {
              alert(resp.data.message);
            });
          this.tackBtn(); //验证码倒数60秒
        }
      });
    },
    getLoginCode() {
      this.$refs["loginForm"].validateField("userPhone", err => {
        if (err) {
          console.log("未通过");
          return;
        } else {
          console.log("已通过");
          this.$http
            .get(
              "/userInfo/sendLoginCode?userPhone=" + this.loginForm.userPhone
            )
            .then(resp => {
              alert(resp.data.message);
            });
          this.loginTackBtn(); //验证码倒数60秒
        }
      });
    },
    tackBtn() {
      //验证码倒数60秒
      let time = 60;
      let timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.valiBtn = "获取验证码";
          this.disabled = false;
        } else {
          this.disabled = true;
          this.valiBtn = time + "秒后重试";
          time--;
        }
      }, 1000);
    },
    loginTackBtn() {
      //验证码倒数60秒
      let time = 60;
      let timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.loginValiBtn = "获取验证码";
          this.loginDisabled = false;
        } else {
          this.loginDisabled = true;
          this.loginValiBtn = time + "秒后重试";
          time--;
        }
      }, 1000);
    },
    loginByaccount(formName){
      this.show=true;
      this.showCode=false;
      this.$refs[formName].resetFields();
    },
    loginByPhone(formName){
      this.show=false;
      this.showCode=true;
      this.$refs[formName].resetFields();
    }
  },
  created() {},
  mounted() {
    const signInBtn = document.getElementById("signIn");
    const signUpBtn = document.getElementById("signUp");
    const fistForm = document.getElementById("form1");
    const secondForm = document.getElementById("form2");
    const container = document.querySelector(".container");

    signInBtn.addEventListener("click", () => {
      container.classList.remove("right-panel-active");
    });

    signUpBtn.addEventListener("click", () => {
      container.classList.add("right-panel-active");
    });

    fistForm.addEventListener("submit", e => e.preventDefault());
    secondForm.addEventListener("submit", e => e.preventDefault());
  }
};
</script>

<style scoped>
@import "../assets/css/login.css";
a {
  text-decoration-line: none;
  color: #11c0b7;
}
.login-transfer{
  text-align: center;
  font-size: 14px;
}

.login-btn-text{
  border: none;
  padding: 0;
  margin: 0;
  outline: none;
  background: none;
  font-size: 14px;
  cursor: pointer;
  transition: all .3s;
  color: #11c0b7;
}
</style>

<style>
:root {
  /* COLORS */
  --white: #e9e9e9;
  --gray: #333;
  --blue: #0367a6;
  --lightblue: #008997;

  /* RADII */
  --button-radius: 0.7rem;

  /* SIZES */
  --max-width: 758px;
  --max-height: 420px;

  font-size: 16px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

@keyframes show {
  0%,
  49.99% {
    opacity: 0;
    z-index: 1;
  }

  50%,
  100% {
    opacity: 1;
    z-index: 5;
  }
}

.el-input__inner::placeholder {
  color: #31e5f5;
}
</style>
